package com.codemonkey.lq.extend.excelverification.impl;

import org.apache.ibatis.io.Resources;

import com.codemonkey.lq.extend.excelverification.AbstractVerifier;
import com.codemonkey.lq.extend.excelverification.CellContext;
import com.codemonkey.lq.extend.excelverification.Verifier;
import com.codemonkey.lq.qd.utils.ClassHelper;

/**
 * 桥接器模式;接收用户自定义实现的验证
 * @author LQ
 *
 */
public class CustomVerifier extends AbstractVerifier {
	private AbstractVerifier underVerifier;

	public CustomVerifier(String customVerifierCls) {
		Class<?> cls = null;
		try {
			cls = Resources.classForName(customVerifierCls);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		// 如果符合要求,才进行构建实例
		if (cls != null && Verifier.class.isAssignableFrom(cls)) {
			underVerifier = ClassHelper.<AbstractVerifier> newInstance(customVerifierCls);
		} else {
			throw new RuntimeException("must implement [ Verifier ] interface");
		}
	}

	@Override
	protected boolean doVerify(CellContext cellContext) {
		boolean match = underVerifier.verify(cellContext);
		if (match) {
			//NO OP 用户自己决定
			//cellContext.setCellVal(cellContext.getCellVal());
		} else {
			StringBuilder sb = new StringBuilder("###");
			sb.append(this.getClass().getSimpleName()).append("[ ");
			sb.append(underVerifier.getClass().getSimpleName()).append(" ]").append(
					System.lineSeparator());

			commonConstructFailContextInfo(cellContext, sb);

			sb.append(underVerifier.getReadableFailMsg(cellContext));
			cellContext.addErrorMsg(sb.toString());
		}

		return match;
	}

	@Override
	public String getReadableFailMsg(CellContext cellContext) {
		return underVerifier.getReadableFailMsg(cellContext);
	}

}
